<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="查询类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="查询类型" style="width: 240px" @change="selectType">
          <el-option key="井号" label="井号" value="well" />
          <el-option key="钻机" label="钻机" value="rig" />
          <el-option key="公司" label="公司" value="company" />
        </el-select>
      </el-form-item>
      <el-form-item v-show="queryParams.type=='well'" label="井号" prop="wellname">
        <el-select v-model="queryParams.wellname" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in wellname"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年份" prop="yearList" v-show="queryParams.type=='well'">
        <el-select v-model="queryParams.yearList" multiple collapse-tags placeholder="年份" style="width: 100%;">
          <el-option v-for="dict in timeYearData" :key="dict" :label="dict" :value="dict" />
        </el-select>
      </el-form-item>
      <el-form-item label="钻机" prop="rigname" v-show="queryParams.type=='rig'">
        <el-input v-model="queryParams.rigname" placeholder="钻机" size="small" style="width: 240px"  />
        <!-- <el-select v-model="queryParams.rig_id" placeholder="钻机" style="width: 100%;">
          <el-option v-for="dict in rigOptions" :key="dict.id" :label="dict.name"
            :value="dict.id" />
          </el-select> -->
      </el-form-item>
      <el-form-item label="公司" prop="company" v-show="queryParams.type=='company'">
        <el-input v-model="queryParams.company" placeholder="公司" size="small" style="width: 240px"  />
        <!-- <el-select v-model="queryParams.companyid" placeholder="公司" style="width: 100%;">
          <el-option v-for="dict in companyOptions" :key="dict.id" :label="dict.name"
            :value="dict.id" />
          </el-select> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" @click="downloadData">数据下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-select v-model="selectKeys" multiple collapse-tags placeholder="显示列" style="width: 100%;">
          <el-option v-for="dict in keys" :key="dict" :label="dict" :value="dict" />
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-select v-model="queryParams.statisticsType" collapse-tags placeholder="统计方式" style="width: 100%;" v-show="queryParams.type=='well'">
          <el-option key="自然年" label="自然年" value="nature" />
          <el-option key="穿时" label="穿时" value="cross" />
        </el-select>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 展示模块 -->
    <el-table v-loading="loading" :data="ledgerList" @selection-change="handleSelectionChange" stripe>
      <el-table-column width="70" align="center" :show-overflow-tooltip="true" />
      <el-table-column align="center" v-for="dict in selectKeys" :prop="dict" :key="dict" :label="dict" width="130"></el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>
import {
  listType,
  listTypeAll,
  listTypeSingle,
  inspectHeaderAll,
  addType,
  dataEche,
  editType,
  delType,
  listCompanyType,
  listRegionType0,
  listRegionType1,
  listRigType,
  addTypeCost,
  downloadLedger,
  getDictList
} from "@/api/vadmin/budget/ledger/ledgerapi";
import chunkUpload from '@/utils/chunkUpload'
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
  name: "statistics",
  data() {
    return {
      // 遮罩层
      loading: true,regionOptions0:[],regionOptions1:[],rigOptions:[],costdetailList:[],wellOptions:[],companyOptions:[],
      selectLedger:{regionname:'',wellname:'',well_type:'',welldepth:'',group:'',rig:'',rigmodel:'',ishx:'',wjzt:''},
      ledgerDict:{'regionname':'区域名称',xmz:'项目组',rig:'钻机',wellname:'井号',welldepth:'井深',ishx:'是否核销',wjzt:'完井状态',
      kzrq:'开钻日期',wzrq:'完钻日期',wjrq:'完井日期',wj:'完井',ljwcjc:'累计完成进尺',sjjc:'设计进尺',year:'统计年度',tjndwcjc:'统计年度完成进尺',syndwcjc:'上一年度完成进尺'},
      // 选中数组
      ids: [],keys:[],selectKeys:[],timeYearData:[],currentYear:2024,
      valNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批复表格数据
      ledgerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,openCost:false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围s
      dateRange: [],
      // 查询参数
      queryParams: {
        isapprove:'已批复',
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        type:'well',wellname: '',year:'2024',rigname:'',company:'',statisticsType:'nature',yearList:['2024']
      },
      wellname:[], //井号
      // 表单参数
      form: {},formCost:{},
      // 表单校验
      rules: {
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },rulesCost:{},
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    debugger
    // 初始化数字台账列表
    this.getLedgerList();
    this.currentYear=new Date().getFullYear();
    this.timeYearData=[]
    for(var i=2020;i<=this.currentYear;i++){
      this.timeYearData.push(i+'')
    }
    this.queryParams.yearList=[this.currentYear+''];
    this.getList()
    this.getDict()
  },
  methods: {
    //查询所有的区域 凹陷 井号
    getDict() {
      console.log('查询所有');
      getDictList(this.addDateRange('aa')).then(response => {
        let res = JSON.parse(Decrypt(response.data));
        //区域数组
        this.region = res.region.flat();
        //凹陷数组
        this.dent = res.dent.flat();
        //井号数组
        this.wellname = res.wellname.flat();

      })
    },
    selectType(){
      console.log(this.queryParams.type)
    },
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    getLedgerList(){
      this.loading = true;
      listType(this.addDateRange({year:this.queryParams.year,pageSize:1000,pageNum:1}, [])).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.wellOptions = resData.results;
        this.wellOptions.push({wellname:'所有',id:'-1'})
        this.loading = false;
      });
    },
    /** 查询数字台账列表 */
    getList() {
      this.loading = true;
      var _this=this
      listTypeSingle(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.ledgerList = resData.results;
        if(this.ledgerList.length==0){
          this.total=0
          this.selectKeys=[]
          this.loading = false;
          return
        }
        debugger
        this.keys=Object.keys(this.ledgerList[0])
        console.log(this.ledgerList[0])
        this.keys.splice(this.keys.findIndex(function(item){return item=='id'}),1)
        this.selectKeys=this.keys
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined,
      };
      this.formCost={
        path: undefined
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.queryParams,'======>');
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //数据下载
    downloadData(){
      debugger
      var fileName = "data.csv"; //使用当前时间戳作为文件名
      var columnDelimiter = ","; //列分割符
      var lineDelimiter = "\r\n"; //行分割符
      var keyValue=this.selectKeys
      let result = ""; // 最终结果的字符串
      for(var i=0;i<keyValue.length;i++){
        result +=this.transferred(keyValue[i]) +columnDelimiter;
      }
      result += lineDelimiter;
      for (var i = 0; i < this.ledgerList.length; i++) {
        for(var j=0;j<keyValue.length;j++){
          console.log(this.ledgerList[i][keyValue[j]])
          result +=this.transferred((this.ledgerList[i][keyValue[j]]+'').replace(/,/g,'')) +columnDelimiter;
        }
        result += lineDelimiter;
      }
      this.downCsvFile(fileName,result)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
     /** 数字台账新增 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this, this.form.id == undefined) {
            addType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          } else {
            editType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    submitCostForm(){
      this.$refs["formCost"].validate(valid => {
        if (valid) {
          if (this, this.formCost.id == undefined) {
            addTypeCost(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.openCost = false;
              this.getList();
            });
          } else {

          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 文件下载 **/
    handleDownload(row) {
      this.download(row.path, row.name);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids;
      dataEche({ "id": row.id }).then((response) => {
        this.form = JSON.parse(Decrypt(response.data));
        this.open = true;
        this.title = "模板修改";
      });
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      this.form.path = data.saveFile
      this.formCost.path = data.saveFile
      this.$message.success('文件上传成功！');
      // inspectHeaderAll({ 'path': data.saveFile }).then(response => {
      //   var resData = JSON.parse(Decrypt(response.data))
      //   if (resData.bol) {
      //     this.form.path = data.saveFile
      //     this.$message.success('文件上传成功！');
      //     this.$refs.uploadRef.clearFiles()
      //   } else {
      //     this.onInspect(resData.repeat_values)
      //   }
      // })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    },
    transferred(data) {
      return data.replace(/<br>/g, "\r\n").replace(/&gt;/g, ">");
    },
    downCsvFile(fileName, result) {
      var fileName = fileName; //使用当前时间戳作为文件名
      var blob = new Blob(["\uFEFF" + result], { type: "text/csv;" }); //记得将编码格式设置一下，避免最终下载的文件出现乱码
      var downloadLink = document.createElement("a");
      if ("download" in downloadLink) {
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = fileName;
        downloadLink.hidden = true;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } else {
        if (navigator.msSaveBlob) {
          //IE10+
          navigator.msSaveBlob(blob, fileName);
        }
      }
    },
  }
};
</script>
   <style scoped>
/* ::v-deep .el-table th.el-table__cell > .cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    white-space: nowrap !important;
} */

  </style>
